package com.wnhoo.smartfishtank.fishtank;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.wnhoo.smartfishtank.R;
import com.wnhoo.smartfishtank.api.LM_PlugAPIs;
import com.wnhoo.smartfishtank.api.data.DataPlug;
import com.wnhoo.smartfishtank.api.data.LM_DataAddDelEdit;
import com.wnhoo.smartfishtank.app.LMAPP;
import com.wnhoo.smartfishtank.base.BaseActivity;
import com.wnhoo.smartfishtank.contants.KContants;
import com.wnhoo.smartfishtank.esptouch.EsptouchTask;
import com.wnhoo.smartfishtank.esptouch.IEsptouchResult;
import com.wnhoo.smartfishtank.esptouch.IEsptouchTask;
import com.wnhoo.smartfishtank.esptouch.demo_activity.EspWifiAdminSimple;
import com.wnhoo.smartfishtank.service.UdpService;
import com.wnhoo.smartfishtank.ui.ProgressWheel;
import com.wnhoo.smartfishtank.util.MyLog;
import com.wnhoo.smartfishtank.util.ShowToastUtil;

public class AddDeviceActivity extends BaseActivity implements BaseActivity.InitHeaderListener {

    private static final String TAG = "AddDeviceActivity";
    protected EditText mSsidEditText;
    protected EditText mPasswordEditText;
    protected Button mStartButton;
    private boolean mIsConncting = false;
    protected Handler mViewHandler = new Handler();
    protected ProgressDialog mWaitingDialog;
    private SharedPreferences sharedPreferences;
    private final String SPF_KEY_WIFI_SSID = "sharedPreferences_key_wifi_ssid";
    private final String SPF_KEY_WIFI_PASSWD = "sharedPreferences_key_wifi_passwd";
    private ProgressWheel progress_bar_four;
    public static AddDeviceActivity instance = null;
    private EspWifiAdminSimple mWifiAdmin;
    private Thread threadAddDevice;
    private boolean isForcedToQuitAddDevice;
    private boolean isSuccessAddDevice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_device);
        setOnInitListener(this);
        initView();
    }

    @Override
    public void initView() {
        super.initView();
        instance = this;
        sharedPreferences = getSharedPreferences(KContants.SPF_PLUG_CONFIG, MODE_PRIVATE);
        mWifiAdmin = new EspWifiAdminSimple(this);
        mSsidEditText = (EditText) findViewById(R.id.edit_wifi_name);
        mPasswordEditText = (EditText) findViewById(R.id.edit_wifi_passwd);
        mStartButton = (Button) findViewById(R.id.btn_start_config);
        progress_bar_four = (ProgressWheel) findViewById(R.id.progressBarFour);
        CheckBox showPwd = (CheckBox) findViewById(R.id.showPwd);
        //如果密码保存了，则直接加载出来
        if (sharedPreferences != null) {
            String spf_wifi_ssid = sharedPreferences.getString(SPF_KEY_WIFI_SSID, null);
            String spf_wifi_passwd = sharedPreferences.getString(SPF_KEY_WIFI_PASSWD, null);
            if (getSSid() != null && !getSSid().equals("<unknown ssid>") && !getSSid().equals("0x") && !getSSid().equals("")) {

                mSsidEditText.setText(getSSid());
                if (spf_wifi_ssid != null && spf_wifi_ssid.equals(getSSid())) {

                    mPasswordEditText.setText(spf_wifi_passwd);
                }
            } else if (spf_wifi_ssid != null) {
                mSsidEditText.setText(spf_wifi_ssid);
                mPasswordEditText.setText(spf_wifi_passwd);
            }
        }
        mSsidEditText.setText(getSSid());
        mSsidEditText.setSelection(mSsidEditText.getText().length());
        mPasswordEditText.setSelection(mPasswordEditText.getText().length());
        //显示或者隐藏密码
        showPwd.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                if (isChecked) {
                    mPasswordEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    mPasswordEditText.setSelection(mPasswordEditText.getText().length());

                } else {
                    mPasswordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    mPasswordEditText.setSelection(mPasswordEditText.getText().length());
                }
            }
        });
        mStartButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
//                if (!mIsConncting) {
                    //设置要配置的ssid 和pswd
                    btnOnclick();
//                }
            }
        });
        IntentFilter intentfilter = new IntentFilter();
        intentfilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        intentfilter.addAction(UdpService.ACTION_BROADCAST_MENU_STATUS);
        registerReceiver(mWifiChangedReceiver, intentfilter);
    }


    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        try {
            isForcedToQuitAddDevice = true;
            unregisterReceiver(mWifiChangedReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean isWiFiConfiging = false;

    /**
     * 配置的点击事件
     */
    public void btnOnclick() {
        if (isWiFiConfiging) {
            ShowToastUtil.show(getApplication(),getStringXml(R.string.configuration));
            return;
        }
        final String str_router_ssid = mSsidEditText.getText().toString();
        final String str_router_passwd = mPasswordEditText.getText().toString();

        if (str_router_ssid.length() <= 0) {
            ShowToastUtil.show(getApplication(), "WiFi名不能为空");
            return;
        }
        if (!(str_router_passwd.length() >= 8 && str_router_passwd.length() <= 63)) {
            ShowToastUtil.show(getApplication(),getStringXml(R.string.password_max));
            return;
        }
        saveWiFi(str_router_ssid, str_router_passwd);
        showProgressDialog();
        String apBssid = mWifiAdmin.getWifiConnectedBssid();
        Log.i(TAG, "=================apBssid" + apBssid);
        new EsptouchAsyncTask2().execute(str_router_ssid, apBssid, str_router_passwd, "NO");
    }

    public void saveWiFi(String router_ssid, String router_passwd) {

        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(SPF_KEY_WIFI_SSID, router_ssid);
        editor.putString(SPF_KEY_WIFI_PASSWD, router_passwd);
        editor.apply();
    }

    BroadcastReceiver mWifiChangedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                if (networkInfo != null && networkInfo.isConnected()) {
                    mSsidEditText.setText(getSSid());
                    mPasswordEditText.requestFocus();
                    mStartButton.setEnabled(true);
                } else {
                    mSsidEditText.setText(getStringXml(R.string.wifi_disconnect));
                    mSsidEditText.requestFocus();
                    mStartButton.setEnabled(false);
                }
            } else if (intent.getAction().equals(UdpService.ACTION_BROADCAST_MENU_STATUS)) {
                sendMessageToUI(WIFI_CONFIG_SUCCESS, 0);
            }

        }
    };
    private int progress;
    private final int sleep_value_fast = 5;
    private int sleep_value;

    /**
     * 让圆形进度条转动起来
     */
    private void showProgressDialog() {

        progress = 0;
        sleep_value = 200;//100*360 = 36s
        isWiFiConfiging = true;

        final Runnable r = new Runnable() {
            public void run() {
                while (progress < 361) {
                    progress_bar_four.incrementProgress();
                    progress++;
                    try {
                        Thread.sleep(sleep_value);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
                progress_bar_four.stopSpinning();
                if (isWiFiConfiging) sendMessageToUI(0, null);
            }
        };
        Thread s = new Thread(r);
        s.start();
    }

    public void sendMessageToUI(int what, Object obj) {

        Message message = Message.obtain();
        message.what = what;
        message.obj = obj;
        updateUIHandler.sendMessage(message);
    }

    public static final int WIFI_CONFIG_SUCCESS = 1;
    public static final int MSG_ADD_DEVICE_TIMEOUT = 8;
    public static final int MSG_ADD_DEVICE_RESULT_HANDLER = 2;
    public static final int MSG_ADD_DEVICE_EXCEPTION_HANDLER = 7;
    public Handler updateUIHandler = new Handler() {

        public void handleMessage(Message msm) {

            switch (msm.what) {
                case WIFI_CONFIG_SUCCESS:
                    //跟设备连接成功，设备返回了自己的类型
                    requestAddDevice(true, LMAPP.dataPlug.getId());
                    break;
                case MSG_ADD_DEVICE_TIMEOUT:
                    //连接服务器超时
//                    requestAddDevice(true, LMAPP.dataPlug.getId());
                    break;
                case MSG_ADD_DEVICE_RESULT_HANDLER:
                    //添加设备请求结果处理
                    handlerRequestAddDeviceResult(msm);
                    break;
                case MSG_ADD_DEVICE_EXCEPTION_HANDLER:

                    break;
                case 0:
//                    ShowToastUtil.show(getApplication(),"配置超时");
                    isWiFiConfiging = false;
                    break;
            }

            super.handleMessage(msm);
        }
    };

    private String getSSid() {

        WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
        if (wm != null) {
            WifiInfo wi = wm.getConnectionInfo();
            if (wi != null) {
                String ssid = wi.getSSID();
                if (ssid.length() > 2 && ssid.startsWith("\"") && ssid.endsWith("\"")) {
                    return ssid.substring(1, ssid.length() - 1);
                } else {
                    return ssid;
                }
            }
        }

        return "";
    }

    @Override
    public void OnSetTitle(TextView t) {
        t.setTextColor(this.getResources().getColor(R.color.ther_text_color));
        t.setText("Add Device");
    }

    @Override
    public void OnSetLeftView(Button btn) {
        btn.setVisibility(View.VISIBLE);
    }

    @Override
    public void OnSetRightView(Button btn) {
        btn.setVisibility(View.VISIBLE);
    }

    @Override
    public void OnSetLeftOnclick(View view) {
    }

    @Override
    public void OnSetRightOnclick(View view) {
    }

    @Override
    public void onSetbackground(View view) {
        view.setBackgroundResource(R.drawable.solid_shadow);
    }


    /**
     * 扫描设备，扫描到设备后，设备返回mac地址
     */
    private class EsptouchAsyncTask2 extends AsyncTask<String, Void, IEsptouchResult> {
        private ProgressDialog mProgressDialog;
        private IEsptouchTask mEsptouchTask;

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected IEsptouchResult doInBackground(String... params) {
            String apSsid = params[0];
            String apBssid = params[1];
            String apPassword = params[2];
            String isSsidHiddenStr = params[3];
            boolean isSsidHidden = false;
            if (isSsidHiddenStr.equals("YES")) {
                isSsidHidden = true;
            }
//            Log.i(TAG,"=================id"+apBssid+":"+apPassword);
            mEsptouchTask = new EsptouchTask(apSsid, apBssid, apPassword, isSsidHidden, AddDeviceActivity.this);
            IEsptouchResult result = mEsptouchTask.executeForResult();
//            Log.i("i", "=====" + result.getInetAddress().getHostName());
            return result;
        }

        @Override
        protected void onPostExecute(IEsptouchResult result) {
            if (!result.isCancelled()) {
                if (result.isSuc()) {
                    Log.i(TAG, "=========id" + result.getBssid());
                    LMAPP.dataPlug = new DataPlug();
                    LMAPP.dataPlug.setId(result.getBssid());

                    Intent intent = new Intent(getApplication(),UdpService.class);
                    startService(intent);
                    Log.i(TAG, "=========id" + result.getBssid());
                }
            }
        }
    }

    /**
     * 向服务器请求添加设备
     *
     * @param deviceId
     */
    public void requestAddDevice(final boolean isSleep, final String deviceId) {

        threadAddDevice = new Thread() {
            @Override
            public void run() {
                super.run();
                long start_timestamp = System.currentTimeMillis();
                long time_out_value_add = 20 * 1000;
                try {
                    if (isSleep) {
                        //MyLog.d(tag,"等待WiFi在重启的...sleep 3s");
                        Thread.sleep(3 * 1000);//WiFi在重启的时候，可以延时
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                while (!isSuccessAddDevice && !isForcedToQuitAddDevice) {
                    try {
                        //MyLog.d(tag,"!isSuccessAddDevice="+!isSuccessAddDevice);
                        //MyLog.d(tag,"!isForcedToQuitAddDevice="+!isForcedToQuitAddDevice);
                        //MyLog.d(tag,"尝试向服务器添加,条件="+(!isSuccessAddDevice||!isForcedToQuitAddDevice));
                        if (System.currentTimeMillis() - start_timestamp >= time_out_value_add) {
                            //超时
                            //MyLog.e(tag,"尝试向服务器添加--超时");
                            isForcedToQuitAddDevice = true;
                            sendMessageToUI(MSG_ADD_DEVICE_TIMEOUT, null);
                            return;
                        }
                        Log.i("i", "=====device_id" + deviceId);
                        //DataAdd dataAdd = PlugAPIs.deviceAdd(true,deviceId,token);
                        String title = getString(R.string.app_name) + deviceId.substring(12);

                        LM_DataAddDelEdit dataAdd = LM_PlugAPIs.deviceAdd(true, deviceId, LMAPP.dataPlug.getType(), title, LMAPP.token_default);
                        Log.i("i", "=====" + deviceId + ":" + title + ":" + LMAPP.token_default);
                        dataAdd.setDeviceId(deviceId);
                        sendMessageToUI(MSG_ADD_DEVICE_RESULT_HANDLER, dataAdd);
                    } catch (Exception e) {
                        //e.printStackTrace();
                        sendMessageToUI(MSG_ADD_DEVICE_EXCEPTION_HANDLER, e);
                    } finally {
                        try {
                            //MyLog.d(tag,"sleep 3s");
                            sleep(3 * 1000);
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                    }
                }
            }
            //MyLog.d(tag,"尝试向服务器添加 End.------------");
        };
        threadAddDevice.start();
    }

    public void handlerRequestAddDeviceResult(Message msg) {

        LM_DataAddDelEdit dataAdd = (LM_DataAddDelEdit) msg.obj;
        int error_code = dataAdd.getError_code();
        String device_id_add = dataAdd.getDeviceId();
//        ShowToastUtil.show(getApplication(),"服务器返回的标识码是"+error_code);
        if (error_code == 0 || error_code == 403 || error_code == 412) {
            //添加成功
            MyLog.d(TAG, "====handlerRequestAddDeviceResult()---向服务器添加成功" + error_code);
//            cancelProgressDialog();
            LMAPP.dataPlug.setAbout("Plug");
            LMAPP.dataPlug.setId(device_id_add);
            LMAPP.dataPlug.setTitle(getString(R.string.app_name) + device_id_add.substring(12));
//            LMAPP.dataPlug.setType(LM_PlugAPIs.TYPE_DEVICE);
            LMAPP.dataPlug.setImage("null");
            LMAPP.dataPlug.setOnline("0");
            LMAPP.dataPlug.setFull_status("0,700");
            //添加设备到SharedPreferences
            isSuccessAddDevice = LMAPP.addPlug(LMAPP.dataPlug);
            //MyLog.d(tag,"handlerRequestAddDeviceResult()---向SharedPreferences添加isSuccessAddDevice="+isSuccessAddDevice);
            if (isSuccessAddDevice) {
                //MyLog.d(tag,"handlerRequestAddDeviceResult()---向SharedPreferences添加成功");
                //ShowToastUtil.show(getApplication(),"添加设备-"+dataPlug.getTitle()+"-成功");
//                showAlert("设备-" + LMAPP.dataPlug.getTitle() + "添加成功");
                Log.i(TAG, "LMAPP.dataPlug" + LMAPP.dataPlug.toString());
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ShowToastUtil.show(getApplication(),getStringXml(R.string.add_device));
                        finish();
                    }
                }, 2000);

            } else {
                isForcedToQuitAddDevice = true;
                //MyLog.d(tag,"handlerRequestAddDeviceResult()---向SharedPreferences添加失败--设备已经存在");
                //ShowToastUtil.show(getApplication(),"设备"+dataPlug.getTitle()+"-已存在");
                ShowToastUtil.show(getApplication(),getStringXml(R.string.device_existing));
                finish();
            }
        } else {
            //MyLog.d(tag,"handlerRequestAddDeviceResult()---向服务器添加失败:"+msg.obj.toString());
            //ShowToastUtil.show(getApplication(),"添加设备失败,"+ LM_ErrorCodeAPIs.getErrorDES(error_code));
            ShowToastUtil.show(getApplication(),getStringXml(R.string.add_device_fail));
            isForcedToQuitAddDevice = true;
            finish();
        }
    }

    public void showAlert(String message) {

        new AlertDialog.Builder(getApplicationContext())
                .setTitle("提示")
                .setMessage(message)
                .setPositiveButton("确定", null)
                .show();

    }
}
